package com.lxhdj.management.security;


import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 *  <p> 访问鉴权 - 每次访问接口都会经过此 </p>
 *
 * @description :
 * @author : zhengqing
 * @date : 2019/10/12 16:17
 */
@Slf4j
public class CustomAuthorizationFilter extends OncePerRequestFilter {

    private SecurityHandler securityHandler;

    public CustomAuthorizationFilter(SecurityHandler securityHandler) {
        this.securityHandler = securityHandler;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        try {


//            SecurityContext context = SecurityContextHolder.getContext();
//            if (context.getAuthentication() != null && context.getAuthentication().isAuthenticated()) {
//                filterChain.doFilter(wrappedRequest, wrappedResponse);
//                return;
//            }

                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("1", "1");

                // 全局注入角色权限信息和登录用户基本信息
                SecurityContextHolder.getContext().setAuthentication(authentication);

            // else {
            //     // 如果没有token则，创建匿名账号防止，通过cookie获取用户
            //     Collection<GrantedAuthority> authorities = new ArrayList<>();
            //     SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_ANONYMOUS");
            //     authorities.add(authority);
            //
            //     SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("anonymousUser",null, authorities));
            // }
            filterChain.doFilter(request, response);

        } catch (AuthenticationException e) {
            SecurityContextHolder.clearContext();
            securityHandler.commence(request, response, e);
        }catch ( IOException | ServletException e){

        }

    }


}
